package com.pp.small.common.interceptor;

import com.pp.small.common.constants.SecurityConstants;
import com.pp.small.common.context.UserContext;
import com.pp.small.common.utils.ServletUtils;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 自定义请求头拦截器，将Header数据封装到线程变量中方便获取
 * 注意：此拦截器会同时验证当前用户有效期自动刷新有效期
 *
 * @author ruoyi
 */
public class AuthInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        if (!(handler instanceof HandlerMethod)) {
            return true;
        }

        // 设置登录用户信息到上下文
        UserContext.setUserId(ServletUtils.getHeader(request, SecurityConstants.USER_ID));
        UserContext.setUserName(ServletUtils.getHeader(request, SecurityConstants.USER_NAME));
        UserContext.setUserKey(ServletUtils.getHeader(request, SecurityConstants.USER_KEY));

        return true;
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) {
        UserContext.remove();
    }
}
